package com.example.project.controller;

import com.alibaba.fastjson.JSON;
import com.example.project.annotations.PassToken;
import com.example.project.common.Result;
import com.example.project.entity.User;
import com.example.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@Slf4j
//@RequestMapping
public class UserController {
    @Autowired
    private UserService userService;

//    员工登录
    @PostMapping("/login")
    @PassToken
    public Result<User> login(HttpServletRequest request, HttpServletResponse response, @RequestBody User user) {
//    public String login(HttpServletRequest request, HttpServletResponse response) {
//        User user = new User();
//        user.setUsername(request.getParameter("username"));
//        user.setPassword(request.getParameter("password"));
        // 获取user
        User user1 = userService.findUser(user.getUsername());

        // 如果为null表示用户不存在
        if (user1 == null) {
            return Result.error("没有该用户!!!");
        }

        // 如果密码不正确返回密码错误
        if (!user1.getPassword().equals(user.getPassword())) {
            return Result.error("密码错误!!!");
        }

        request.getSession().setAttribute("userName", user.getUsername());

        // 获取token
        String newToken = userService.getToken(user1, 60* 60 * 1000);
        String newRefToken = userService.getToken(user1, 24*60*60*1000);
        log.info(user1.toString());

        // 更新token
        response.setHeader("Authorization", newToken);
        response.setHeader("freshToken", newRefToken);


        return Result.success(user1);
    }

    // 员工注册
    @PostMapping("register")
    @PassToken
    public String register(@RequestBody User user) {
//    public String register(HttpServletRequest request) {
//        User user = new User();
//        user.setName(request.getParameter("name"));
//        user.setUsername(request.getParameter("username"));
//        user.setPassword(request.getParameter("password"));
//        user.setPhone(request.getParameter("phone"));
//        user.setSex(request.getParameter("sex"));
        log.info(user.toString());
        // 判断传入数据是否正确
        if (user == null) {
            return JSON.toJSONString(Result.error("数据不正确!!!"));
        }

        userService.saveUser(user);

        return JSON.toJSONString(Result.success("新增用户成功!!!"));
    }
}
